package com.hds.modules.sys.utils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author guonan
 * @Email guonan@yewcn.com
 * @Description
 * @Date 2018/8/1 16:41
 */
public class DownloadUtil {
    public static void main(String[] args) {
        try{
            readfile("F:\\Document\\sts-workspace\\hds_pro\\dto\\excel");
        }catch(Exception e){
        }

    }

    /**
     * 读取某个文件夹下的所有xls文件
     */
    public static List<String> readfile(String filepath) throws IOException {
        try {
            List<String> list = new ArrayList<>();
            File file = new File(filepath);
            if (file.isDirectory()) {
                String[] files = file.list();
                for (String f : files) {
                    list.add(f);
                }

            }
            return list;
        } catch (Exception e) {
            e.getStackTrace();
        }
            return null;
    }




    public static void download(HttpServletResponse resp, String name, String downloadName, String realPath) {
        String fileName = null;
        try {
            fileName = new String(downloadName.getBytes("GBK"), "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        String path = realPath + File.separator + name;
        File file = new File(path);


        // 取得文件名。
        String filename = file.getName();
        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toLowerCase();
        System.out.println("后缀："+ext);



        resp.reset();
        resp.setContentType("application/octet-stream");
        resp.setCharacterEncoding("utf-8");
        resp.setContentLength((int) file.length());
        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName+"."+ext);
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = resp.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




}
